<template>
	<el-dialog title="添加爱好" width="80vw" :visible.sync="show" @close="close" :close-on-click-modal='false'>
		<el-form :model="formData" ref="VideoCateFrom">
			<el-form-item label="爱好">
				<el-tooltip content="只支持中文、英文、数字的爱好(最多10个字符)" placement="top" :hide-after="1000">
					<div>
						<el-tag :key="tag" v-for="tag in hobbyTags" closable class="video-tag"
							:disable-transitions="false" @close="tagRemove(tag)">{{tag}}</el-tag>
						<el-input class="input-new-tag" v-if="inputVisible" v-model="inputTag" ref="saveTagInput"
							size="small" maxlength="10" @keyup.enter.native="handleInputConfirm"
							@blur="handleInputConfirm"
							οnkeyup="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
							οnpaste="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
							oncontextmenu="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')">
						</el-input>
						<el-button v-else-if="hobbyTags.length<tagMaxNumber" class="button-new-tag" size="small"
							@click="showInput">添加爱好</el-button>
					</div>
				</el-tooltip>

			</el-form-item>
			<el-form-item label="">
				<el-input placeholder="输入内容进行搜索" v-model="keyword" @keyup.enter.native.stop="handleInputNameChange"
					clearable>
					<el-button slot="append" icon="el-icon-search" @click="handleInputNameChange" class="serach-btn">
					</el-button>
				</el-input>
			</el-form-item>
			<el-form-item label="热门爱好">
				<!-- 默认 -->
				<template>
					<el-checkbox-group v-model="checkedCitiesO" @change="handleCheckedCitiesChangeO">
						<el-checkbox v-for="(item,index) in hotTagListO" :label="item.hobbyname" :key="item.id"
							:disabled='hobbyTags.length>=tagMaxNumber'>
							{{item.hobbyname}}
						</el-checkbox>
					</el-checkbox-group>
				</template>
				<!-- 搜索 -->
				<template>
					<el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
						<el-checkbox v-for="(item,index) in hotTagList" :label="item.hobbyname" :key="item.id"
							:disabled='hobbyTags.length>=tagMaxNumber'>
							{{item.hobbyname}}
						</el-checkbox>
					</el-checkbox-group>
				</template>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="confirm" :disabled='inputVisible'>确定</el-button>
				<el-button @click="close">取消</el-button>
			</el-form-item>
		</el-form>
	</el-dialog>
</template>

<script>
	import {
		getType
	} from "@/utils/base";
	import {
		getHobby,
		setHobby
	} from "@/api/hobby";
	// ///字典接口
	import {
		getInfo
	} from "@/api/dict";
	export default {
		data() {
			return {
				show: false,
				hobbyTags: [], // 动态爱好列表
				inputVisible: false, // 爱好输入框可见
				inputTag: "",
				keyword: "", //搜索爱好
				formData: {},
				hotTagList: [], //热门爱好
				hotTagListO: [], //默认--热门爱好
				checkedCities: [], //选过的热门爱好
				checkedCitiesO: [], //默认--选过的热门爱好
				oldcheckedCities: [], //原 选过的热门爱好
				oldcheckedCitiesO: [], //默认--原 选过的热门爱好
				tagMaxNumber: 6,
				isImplementation: 0
			}
		},

		methods: {
			init() {
				if (this.isImplementation) {
					return
				}
				this.isImplementation = 1
				let obj = {
					code: 'tagMaxNumber'
				};
				getInfo(obj).then(res => {
					try {
						if (res.data && res.data.length > 0) {
							
							if (isNaN(parseInt(res.data[0].value))) {
							  throw new Error("value不是数字类型");
							}else{
								this.tagMaxNumber = parseInt(res.data[0].value);
							}
						}
					} catch (err) {
						this.tagMaxNumber = 6
						if(err.message!="value不是数字类型"){
							this.$message.error( err.message);
						}
					}
				});
				getHobby({
					pageNum: 1,
					pageSize: 10
				}).then(res => {
					this.hotTagListO = res.data
				})
			},
			openShow(res) {
			    this.init();
			    this.show = true;
			
			    if (Array.isArray(res) && res.length > 0) {
			        this.hobbyTags = res;
			        this.checkedCities = [...res];
			        this.checkedCitiesO = [...res];
			        this.oldcheckedCitiesO = [...res];
			        this.oldcheckedCities = [...res];
			    } else {
			        this.hobbyTags = [];
			        this.checkedCities = [];
			        this.checkedCitiesO = [];
			        this.oldcheckedCitiesO = [];
			        this.oldcheckedCities = [];
			    }
			},
			// openShow(res) {
			// 	this.init()
			// 	this.show = true;
			// 	if (typeof res != "string" && res != null && res != undefined) {
			// 		this.hobbyTags = res
			// 		this.checkedCities = [...this.checkedCities, ...res]
			// 		this.checkedCitiesO = [...this.checkedCitiesO, ...res]
			// 		this.oldcheckedCitiesO = [...this.checkedCitiesO]
			// 		this.oldcheckedCities = [...this.checkedCities]
			// 	} else {
			// 		this.hobbyTags =
			// 			this.checkedCities =
			// 			this.checkedCitiesO =
			// 			this.oldcheckedCitiesO =
			// 			this.oldcheckedCities = []
			// 	}

			// },
			close() {
			    this.show = false;
			    this.hobbyTags = [];
			    this.checkedCities = [];
			    this.checkedCitiesO = [];
			    this.oldcheckedCitiesO = [];
			    this.oldcheckedCities = [];
			    this.keyword = ""; // 清空搜索关键词
			},
			confirm() {
				let array = new Set(this.hobbyTags);
				this.$emit('selected', Array.from(array))
				this.close();
			},
			// // 爱好移除
			tagRemove(tag) {
			    let hobbyTagsIndex = this.hobbyTags.indexOf(tag);
			    let checkedCitiesIndex = this.checkedCities.indexOf(tag);
			    let checkedCitiesOIndex = this.checkedCitiesO.indexOf(tag);
			
			    if (hobbyTagsIndex !== -1) {
			        this.hobbyTags.splice(hobbyTagsIndex, 1);
			    }
			    if (checkedCitiesIndex !== -1) {
			        this.checkedCities.splice(checkedCitiesIndex, 1);
			    }
			    if (checkedCitiesOIndex !== -1) {
			        this.checkedCitiesO.splice(checkedCitiesOIndex, 1);
			    }
			},
			// 显示爱好输入框
			showInput() {
				this.inputVisible = true;
				this.$nextTick(_ => {
					this.$refs.saveTagInput.$refs.input.focus();
				});
			},
			// 新增爱好确认
			handleInputConfirm(val, type) {
				let that = this;
				let inputTag = that.inputTag || val;

				if (!inputTag || getType(inputTag).indexOf('event') != -1) {
					that.inputVisible = false;
					that.inputTag = "";
					return
				}
				//正则匹配
				inputTag = inputTag.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g, '')
				try {
					that.hobbyTags.forEach((item, index, array) => {
						if (inputTag == item) {
							that.$message({
								message: "已存在相同爱好，换一个试试吧",
								type: "warning"
							})
							throw new Error('beng~')
						}
					})
					//true 直接添加
					if (type) {
						//添加
						if (inputTag) {
							that.hobbyTags.push(inputTag);
							let array = new Set(that.hobbyTags);
							let newArr = Array.from(array)
							if (newArr.length != that.hobbyTags.length) {
								that.hobbyTags = newArr
							}
						}
						that.inputVisible = false;
						that.inputTag = "";
					} else {
						// 敏感词检测
						// detectingWord({
						// 	content: inputTag
						// }).then(res => {
						// 	if (res.data) {
						// 		that.$message.warning("检测到有敏感词存在，请检查后重新填写");
						// 		that.inputTag = "";
						// 		return;
						// 	} else {
						// 		//添加
						if (inputTag) {
							that.hobbyTags.push(inputTag);
							let array = new Set(that.hobbyTags);
							let newArr = Array.from(array)
							if (newArr.length != that.hobbyTags.length) {
								that.hobbyTags = newArr
							}

						}
						that.inputVisible = false;
						that.inputTag = "";
						// 	}
						// });
					}

				} catch (e) {
					//TODO handle the exception
				}
			},
			//爱好搜索
			handleInputNameChange() {
				if (!this.keyword) {
					return
				}
				getHobby({
					pageNum: 1,
					pageSize: 10,
					hobbyname: this.keyword
				}).then(res => {
					this.hotTagList = res.data
					if (res.data.length === 0) {
						this.$message({
							message: "暂无数据",
							type: "info",
							duration: 700
						})
					}
				})
			},
			async handleCheckedCitiesChangeO(array) {
				let that = this;
				let oldArray = this.oldcheckedCitiesO
				//获取交集
				let arr3 = []; //用来接收交集
				arr3 = await array.filter((it) => oldArray.includes(it))
				// 需要删除的数组
				for (let key in oldArray) {
					if (arr3.indexOf(oldArray[key]) === -1) {
						let hobbyTagsIndex = that.hobbyTags.indexOf(oldArray[key]);
						if (hobbyTagsIndex != -1) {
							that.hobbyTags.splice(hobbyTagsIndex, 1);
						}
						// that.hobbyTags.splice(that.hobbyTags.indexOf(oldArray[key]), 1)
					}
				}
				//添加爱好
				array.forEach((item, index, array) => {
					if (that.hobbyTags.indexOf(item) === -1) {
						that.handleInputConfirm(item, true)
					}
				})
				//替换
				this.oldcheckedCitiesO = Object.assign([], array);
			},
			//选中改变  id 数组
			handleCheckedCitiesChange(array) {
				let that = this;
				let oldArray = this.oldcheckedCities
				let arr3 = []; //用来接收交集
				let hashmap = {}; //定义一个hashmap对象
				oldArray.forEach(function(element) {
					hashmap[element] = 1;
				})
				array.forEach(function(element) {
					if (hashmap[element] === 1) {
						arr3.push(element);
						hashmap[element]++; //设置计数器跟踪我们已添加的内容
					}
				})
				// 需要删除的数组
				for (let key in oldArray) {
					if (arr3.indexOf(oldArray[key]) === -1) {
						let hobbyTagsIndex = that.hobbyTags.indexOf(oldArray[key]);
						if (hobbyTagsIndex != -1) {
							that.hobbyTags.splice(hobbyTagsIndex, 1);
						}
						// that.hobbyTags.splice(that.hobbyTags.indexOf(oldArray[key]), 1)
					}
				}
				//添加爱好
				array.forEach((item, index, array) => {
					if (that.hobbyTags.indexOf(item) === -1) {
						that.handleInputConfirm(item, true)
					}
				})
				//替换
				this.oldcheckedCities = Object.assign([], array);
			}

		},
		watch: {
			keyword(value) {
				if (!value) {
					this.handleInputNameChange()
				}
			}
		}
	}
</script>

<style scoped>
	.hobby-tag {
		margin-right: 10px;
	}

	.button-new-tag {
		height: 32px;
		line-height: 30px;
		padding-top: 0;
		padding-bottom: 0;
	}

	.input-new-tag {
		width: 90px;
		vertical-align: bottom;
	}

	.checkboxC {
		margin-top: 10px;
	}

	/deep/ .el-checkbox__input.is-disabled+span.el-checkbox__label {
		color: #727579;
	}
</style>